import json
import logging
import logging.handlers
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from config import TIPS_MSG_LOC


class DriverUtil:
    __driver = None

    @classmethod
    def get_driver(cls):
        if cls.__driver is None:
            cls.__driver = webdriver.Chrome()
            cls.__driver.maximize_window()
            return cls.__driver
        return cls.__driver

    @classmethod
    def quit_driver(cls):
        if cls.__driver is not None:
            cls.__driver.quit()
            cls.__driver = None


def get_tips_msg(timeout=10):
    el = WebDriverWait(DriverUtil.get_driver(), timeout).until(lambda x: x.find_element(*TIPS_MSG_LOC))
    # msg = el.text
    msg = el.get_attribute("textContent")
    return msg


def readJson(filename):
    with open(filename, "r", encoding="utf8") as f:
        res = json.load(f)
        my_list = []
        for i in res:
            values = tuple(i.values())
            my_list.append(values)
    return my_list


def init_log_config(filename, when='midnight', interval=1, backup_count=7):
    """
    功能：初始化日志配置函数
    :param filename: 日志文件名
    :param when: 设定日志切分的间隔时间单位
    :param interval: 间隔时间单位的个数，指等待多少个 when 后继续进行日志记录
    :param backup_count: 保留日志文件的个数
    :return:
    """
    # 1. 创建日志器对象
    logger = logging.getLogger()

    # 2. 设置日志打印级别
    logger.setLevel(logging.INFO)
    # 通常在开发的时候, 设置为DEBUG级别, 以便于输出所有信息
    # 通常在上线的时候, 设置为INFO级别. DEBUG信息只是给程序员在开发时用的, 上线的时候没必要打印
    # logging.DEBUG 调试级别
    # logging.INFO 信息级别
    # logging.WARNING 警告级别
    # logging.ERROR 错误级别
    # logging.CRITICAL 严重错误级别

    # 3. 创建处理器对象
    # 控制台对象
    st = logging.StreamHandler()
    # 日志文件对象
    fh = logging.handlers.TimedRotatingFileHandler(filename,
                                                   when=when,
                                                   interval=interval,
                                                   backupCount=backup_count,
                                                   encoding='utf-8')

    # 4. 日志信息格式
    fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
    formatter = logging.Formatter(fmt)

    # 5. 给处理器设置日志信息格式
    st.setFormatter(formatter)
    fh.setFormatter(formatter)

    # 6. 给日志器添加处理器
    logger.addHandler(st)
    logger.addHandler(fh)
